package com.inspectortime.webapp.inspector;

import org.springframework.util.StringUtils;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

import com.inspectortime.domain.RealEstateAgent;
import com.inspectortime.repository.Repository;
import com.inspectortime.util.SpringValidatorUtils;
import com.mkode.util.java.lang.ClassUtils;

/**
 * @author mkvalsvik
 * 
 */
public class EditReferringRealtorFormValidator implements Validator {
	
	private Repository repository;
	private boolean skipEmailConfirmFieldValidation;

	public boolean supports(Class clazz) {
		return ClassUtils.isInstanceOf(clazz, RealEstateAgent.class);
	}

	public void validate(Object obj, Errors errors) {
		RealEstateAgent agent = (RealEstateAgent) obj;
		
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name.first","required");
		SpringValidatorUtils.rejectIfTooLong(errors, "name.first", "tooLong", 50);
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name.last", "required");
		SpringValidatorUtils.rejectIfTooLong(errors, "name.last", "tooLong", 50);
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "company", "required");
		SpringValidatorUtils.rejectIfTooLong(errors, "company", "tooLong", 100);
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "email", "required");
		SpringValidatorUtils.rejectIfTooLong(errors, "email", "tooLong", 100);
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "cellPhone", "required");
		SpringValidatorUtils.rejectInvalidPhone(errors, "cellPhone");
		SpringValidatorUtils.rejectInvalidEmail(errors, "email");
		
		if (!skipEmailConfirmFieldValidation) {
			ValidationUtils.rejectIfEmptyOrWhitespace(errors, "emailConfirm", "required.emailConfirm");
			SpringValidatorUtils.validateEmailConfirm(errors, "email", "emailConfirm");
		}
		
		if (StringUtils.hasText(agent.getOffice())) {
			SpringValidatorUtils.rejectIfTooLong(errors, "office", "tooLong", 100);
		}
		
	}
	
	public void setRepository(Repository repository) {
		this.repository = repository;
	}

	public void setSkipEmailConfirmFieldValidation(
			boolean skipEmailConfirmFieldValidation) {
		this.skipEmailConfirmFieldValidation = skipEmailConfirmFieldValidation;
	}


}
